package doweb

import (
	"fmt"
	"github.com/buaazp/fasthttprouter"
	"github.com/valyala/fasthttp"
	"strings"
)

var router *fasthttprouter.Router

func init() {
	router = fasthttprouter.New()
}

//AddRouter 123
func AddRouter(method string, path string, handle fasthttp.RequestHandler) {
	router.Handle(method, path, handle)
}

//Index 13
func Index(ctx *fasthttp.RequestCtx) {
	// fmt.Println(ClientIP(ctx))
	// ctx.Request.Header.Peek("userid") //获取header头参数
	fmt.Fprint(ctx, "Welcome")

}

//Start 13
func Start(port string) {
	fmt.Println(fasthttp.ListenAndServe(":"+port, router.Handler))
}

//ClientIP 123
func ClientIP(ctx *fasthttp.RequestCtx) string {
	clientIP := string(ctx.Request.Header.Peek("X-Forwarded-For"))
	if index := strings.IndexByte(clientIP, ','); index >= 0 {
		clientIP = clientIP[0:index]
		//获取最开始的一个 即 1.1.1.1
	}
	clientIP = strings.TrimSpace(clientIP)
	if len(clientIP) > 0 {
		return clientIP
	}
	clientIP = strings.TrimSpace(string(ctx.Request.Header.Peek("X-Real-Ip")))
	if len(clientIP) > 0 {
		return clientIP
	}
	return ctx.RemoteIP().String()
}
